using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Text;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

using Microsoft.SharePoint;
using Microsoft.SharePoint.Administration;
using Microsoft.SharePoint.Utilities;

namespace CKS.EWE.WikiDiscussion
{
    [DefaultProperty("Text")]
    [ToolboxData("<{0}:WikiTopicItemButton runat=server></{0}:WikiTopicItemButton>")]
    public class WikiTopicItemButton : Microsoft.SharePoint.WebControls.FormButton
    {
        // Create the "Return to Topic" button used on the Wiki Discussion view page.
        // Instance specified in control template SharePoint:RenderingTemplate ID="DiscussionMiniConsole"
        string _wikiLib;
        //string _discussionLib;

        #region PROPERTIES

        [Bindable(true)]
        [DefaultValue("Wiki Pages")]
        [Localizable(true)]
        public string WikiPagesLibraryName
        {
            get
            {
                if (_wikiLib == null) _wikiLib = "Wiki Pages";
                return _wikiLib;
            }
            set
            {
                _wikiLib = value;
            }
        }

        //[Bindable(true)]
        //[DefaultValue("Wiki Discussions")]
        //[Localizable(true)]
        //public string DiscussionLibraryName
        //{
        //    get
        //    {
        //        if (_discussionLib == null) _discussionLib = "Wiki Discussions";
        //        return _discussionLib;
        //    }
        //    set
        //    {
        //        _discussionLib = value;
        //    }
        //}


        #endregion

        protected override void Render(HtmlTextWriter output)
        {

            SPContext SiteContext = null;
            SPWeb WikiWeb = null;
            SPList DiscList = null;
            SPListItem DiscItem = null;

            Guid WikiListGuid, WikiItemGuid;
            string WikiListGuidString, WikiItemGuidString;
            SPList WikiPages = null;
            SPListItem WikiPage = null;

            try
            {
                // Get current Site and Web
                SiteContext = SPContext.GetContext(HttpContext.Current);
                WikiWeb = SiteContext.Web;

                //// Get current Discussion list
                //ListGuid = Util.GetListGuid(WikiWeb, DiscussionLibraryName);
                //if (ListGuid == Guid.Empty) throw new ApplicationException("Discussion board [" + DiscussionLibraryName + "] for this wiki site was not found");
                //DiscList = WikiWeb.Lists[ListGuid];
                DiscList = SiteContext.List;

                DiscItem = Util.GetDiscItem(DiscList, HttpContext.Current);
                if (DiscItem != null)
                {
                    try
                    {
                        if (DiscItem["WikiListGuid"] != null)
                        {
                            WikiListGuidString = DiscItem["WikiListGuid"].ToString();
                            WikiListGuid = (Guid)TypeDescriptor.GetConverter(typeof(Guid)).ConvertFrom(WikiListGuidString);
                            WikiPages = WikiWeb.Lists[WikiListGuid];
                        }
                        else
                        {
                            // Get current Wiki page library and Page
                            WikiListGuid = Util.GetListGuid(WikiWeb, WikiPagesLibraryName);
                            if (WikiListGuid == Guid.Empty) throw new ApplicationException("Wiki library [" + WikiPagesLibraryName + "] configured for discussion board was not found");
                            WikiPages = WikiWeb.Lists[WikiListGuid];
                        }

                    
                        if (DiscItem["WikiItemGuid"] != null)
                        {
                            WikiItemGuidString = DiscItem["WikiItemGuid"].ToString();
                            WikiItemGuid = (Guid)TypeDescriptor.GetConverter(typeof(Guid)).ConvertFrom(WikiItemGuidString);
                            WikiPage = WikiPages.Items[WikiItemGuid];

                            // Render the sucker
                            RenderButton(output, WikiPages.ParentWebUrl + "/" + WikiPage.Url);
                        }
                    }
                    catch
                    {
                        // Wiki list or item missing.
                        Util.RenderMessage(output, "*", "This discussion entry has no associated wiki topic.");
                    }

                }
            }
            catch (Exception ex)
            {
                Util.LogException(output, ex);
            }
            finally
            {
                if (WikiWeb != null)
                {
                    //WikiWeb.Dispose();
                }
            }

        }


        protected void RenderButton(HtmlTextWriter output, string encodedURL)
        {
            // Render the button.  Most properties of this button come from the control
            // template WikiTopicTemplate.ascx or WikiDiscussionTemplate.  The destination URL is
            // computed to match the appropriate discussion topic, and passed to this routine.

            string altText;

            output.Write("<table cellpadding='1' cellspacing='0'");
            if (this.ToggleOn)
            {
                output.Write(" class='ms-toolbar-togglebutton-on'");
            }
            output.Write(">");
            output.Write("<tr>");

            if (string.IsNullOrEmpty(this.ToolTip))
            {
                altText = base.Text;
            }
            else
            {
                altText = this.ToolTip;
            }

            output.Write("<td class='ms-toolbar' nowrap");
            if (!string.IsNullOrEmpty(this.Padding))
            {
                output.Write(" style=\"padding: ");
                output.Write(SPHttpUtility.HtmlEncode(this.Padding));
                output.Write("\"");
            }
            output.Write(">");

            output.Write("<a ");
            output.Write(" href='" + encodedURL + "'");
            output.Write(" class='ms-toolbar'");
            output.Write(">");

            RenderImage(output, altText, "width='16' height='16'"); //render this.ImageURL if specified
            output.Write("</a>");
            output.Write("</td>");

            output.Write("<td class='ms-toolbar' nowrap");
            if (!string.IsNullOrEmpty(this.Padding))
            {
                output.Write(" style=\"padding: ");
                output.Write(SPHttpUtility.HtmlEncode(this.Padding));
                output.Write("\"");
            }
            output.Write(">");

            output.Write("<a ");
            output.Write(" href='" + encodedURL + "'");
            output.Write(" class='ms-toolbar'");
            output.Write(" title='" + altText + "'");
            output.Write(">");

            output.Write(base.Text);
            output.Write("</a>");
            output.Write("</td>");

            output.Write("</tr></table>");
        }

    }
}
